<?php
//自动生成,请根据需要修改
namespace app\user\controller;

use app\common\controller\Base;
use think\Db;
use think\Validate;

/**
 * @title 用户信息页面（模块01-01）
 * @description 用户信息说明
 * @group 用户中心（01）
 * @header name:model_id require:0 default:01-01 desc:模块
 * @groupremark 已使用错误码：1-01-01-0001 校验失败 1-01-01-0002 添加失败 1-01-01-0003 编辑校验失败 1-01-01-0004 编辑失败 1-01-01-0005 获取详情失败  1-01-01-0006 获取列表失败 1-01-01-0007获取单个详情失败 1-01-01-0008 删除失败
 */
class User extends Base
{
    //测试
    public function test()
    {
        return 'test 111';
    }

    /**
     * @title 添加用户信息
     * @description 添加用户信息
     * @author 李锐志
     * @edit_time 2018-12-27
     * @author 宋晓文
     * @url /user/user/add
     * @method *
     * @header name:token require:1 default: desc:token
     * @param name:nickname type:varchar require:0 other: desc:昵称
     * @param name:point_value type:int require:0 other: desc:积分
     * @param name:signature type:varchar require:0 other: desc:个性签名
     * @param name:head_img type:varchar require:0 other: desc:头像
     * @param name:sex type:enum require:0 other: desc:性别.男:man;女:woman;保密:secrecy
     * @param name:hometown type:varchar require:0 other: desc:家乡
     * @param name:phone type:varchar require:0 other: desc:手机
     * @param name:password type:varchar require:0 other: desc:密码
     * @param name:position type:varchar require:0 other: desc:职位
     * @param name:qr_code type:varchar require:0 other: desc:微信二维码
     * @param name:message_quantity type:int require:0 other: desc:站内信数量
     * @param name:user_type type:enum require:0 other: desc:用户类型.普通用户:common_user;设计师:stylist;心理师:psychologist
     * @param name:introduce type:enum require:0 other: desc:介绍(只有设计师和心理师有介绍)
     * @param name:is_show type:tinyint require:0 other: desc:是否首页显示
     * @return data:用户信息@!
     * @data    id:id    nickname:昵称    point_value:积分    signature:个性签名    head_img:头像    sex:性别.男:man;女:woman;保密:secrecy    hometown:家乡    phone:手机    password:密码    position:职位    qr_code:微信二维码    message_quantity:站内信数量    user_type:用户类型.普通用户:common_user;设计师:stylist;心理师:psychologist    is_show:是否首页显示
     * @return error_id:1-01-01-0001 校验失败  1-01-01-0002 添加失败
     */
    public function add()
    {
        $data = input();
        $data['password'] = md5($data['password']);
        $model = new \app\user\model\User();

        if (preg_match("/^[1][3-9][0-9]{9}$/", $data['phone']) == false) {
            $msg['error_id'] = '1-01-01-0001';
            $msg['msg'] = '手机号不正确';
            $msg['status'] = 'false';
            return $this->errorJson($msg);
        } else {
            $user = $model->where('phone', $data['phone'])->find();
            if ($user) {
                $msg['error_id'] = '1-01-01-0001';
                $msg['msg'] = '手机号已存在';
                $msg['status'] = 'false';
                return $this->errorJson($msg);
            }
        }
        /**
         *$validate = new \app\user\validate\User();
         *$validate->scene('add');
         *$result = $validate->batch(true)->check($data);
         *if ($result !== true) {
         *$msg['msg']='校验失败';
         *$msg['validate']=$validate->getError();
         *$msg['error_id']='1-01-01-0001';
         *return $this->errorJson($msg);
         *}
         **/
        $flag = $model->save($data);
        if ($flag) {
            $msg['msg'] = '添加成功';
            $msg['data'] = $model->get($model['id']);
            return $this->successJson($msg);
        } else {
            $msg['error_id'] = '1-01-01-0002';
            $msg['msg'] = '添加失败';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 编辑用户信息
     * @description 编辑用户信息
     * @author 李锐志
     * @url /user/user/edit
     * @method *
     * @header name:token require:1 default: desc:token
     * @param name:id type:int require:0 other: desc:id
     * @param name:nickname type:varchar require:0 other: desc:昵称
     * @param name:point_value type:int require:0 other: desc:积分
     * @param name:signature type:varchar require:0 other: desc:个性签名
     * @param name:head_img type:varchar require:0 other: desc:头像
     * @param name:sex type:enum require:0 other: desc:性别.男:man;女:woman;保密:secrecy
     * @param name:hometown type:varchar require:0 other: desc:家乡
     * @param name:phone type:varchar require:0 other: desc:手机
     * @param name:password type:varchar require:0 other: desc:密码
     * @param name:position type:varchar require:0 other: desc:职位
     * @param name:qr_code type:varchar require:0 other: desc:微信二维码
     * @param name:message_quantity type:int require:0 other: desc:站内信数量
     * @param name:user_type type:enum require:0 other: desc:用户类型.普通用户:common_user;设计师:stylist;心理师:psychologist
     * @param name:introduce type:enum require:0 other: desc:介绍(只有设计师和心理师有介绍)
     * @param name:is_show type:tinyint require:0 other: desc:是否首页显示
     * @return data:用户信息@!
     * @data    id:id    nickname:昵称    point_value:积分    signature:个性签名    head_img:头像    sex:性别.男:man;女:woman;保密:secrecy    hometown:家乡    phone:手机    password:密码    position:职位    qr_code:微信二维码    message_quantity:站内信数量    user_type:用户类型.普通用户:common_user;设计师:stylist;心理师:psychologist    is_show:是否首页显示
     * @return error_id:1-01-01-0003 校验失败 1-01-01-0004 修改失败
     */
    public function edit()
    {
        $data = input();
        $validate = new \app\user\validate\User();
        $validate->scene('edit');
        $result = $validate->batch(true)->check($data);
        if ($result !== true) {
            $msg['msg'] = '校验失败';
            $msg['validate'] = $validate->getError();
            $msg['error_id'] = '1-01-01-0003';
            return $this->errorJson($msg);
        }
        $model = new \app\user\model\User();
        $flag = $model->edit($data);
        if ($flag !== false) {
            $msg['msg'] = '修改成功';
            $msg['data'] = $model->get($data['id']);
            return $this->successJson($msg);
        } else {
            $msg['error_id'] = '1-01-01-0004';
            $msg['msg'] = '修改失败';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 删除用户信息
     * @description 删除用户信息
     * @author 李锐志
     * @url /user/user/delete
     * @method *
     * @param name:token require:1 default: desc:token
     * @param name:id type:int|array require:1 other: desc:要删除的id
     * @return error_id:1-01-01-0008 删除失败
     */
    public function delete()
    {
        $id = input('id');
        $model = new \app\user\model\User();
        $flag = $model->destroy($id);
        if ($flag) {
            $msg['msg'] = '删除成功';
            return $this->successJson($msg);
        } else {
            $msg['msg'] = '删除失败';
            $msg['error_id'] = '1-01-01-0008';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 单个查询用户信息
     * @description 单个查询用户信息
     * @author 李锐志
     * @url /user/user/info
     * @method *
     * @param name:token require:1 default: desc:token
     * @param name:id type:int require:0 other: desc:id
     * @param name:nickname type:varchar require:0 other: desc:昵称
     * @param name:point_value type:int require:0 other: desc:积分
     * @param name:signature type:varchar require:0 other: desc:个性签名
     * @param name:head_img type:varchar require:0 other: desc:头像
     * @param name:sex type:enum require:0 other: desc:性别.男:man;女:woman;保密:secrecy
     * @param name:hometown type:varchar require:0 other: desc:家乡
     * @param name:phone type:varchar require:0 other: desc:手机
     * @param name:password type:varchar require:0 other: desc:密码
     * @param name:position type:varchar require:0 other: desc:职位
     * @param name:qr_code type:varchar require:0 other: desc:微信二维码
     * @param name:message_quantity type:int require:0 other: desc:站内信数量
     * @param name:user_type type:enum require:0 other: desc:用户类型.普通用户:common_user;设计师:stylist;心理师:psychologist
     * @param name:introduce type:enum require:0 other: desc:介绍(只有设计师和心理师有介绍)
     * @param name:is_show type:tinyint require:0 other: desc:是否首页显示
     * @return data:用户信息@!
     * @data    id:id    nickname:昵称    point_value:积分    signature:个性签名    head_img:头像    sex:性别.男:man;女:woman;保密:secrecy    hometown:家乡    phone:手机    password:密码    position:职位    qr_code:微信二维码    message_quantity:站内信数量    user_type:用户类型.普通用户:common_user;设计师:stylist;心理师:psychologist    is_show:是否首页显示
     * @return error_id:1-01-01-0005 校验失败 1-01-01-0007 获取失败
     */
    public function info()
    {
        $model = new \app\user\model\User();
        $Fields = $model->getTableFields();
        $data = \think\facade\Request::only($Fields);
        /**
         *$validate = new \app\user\validate\User();
         *$validate->scene('info');
         *$result = $validate->batch(true)->check($data);
         */
        if (!$data) {
            $msg['msg'] = '必须有参数';
            $msg['error_id'] = '1-01-01-0005';
            return $this->errorJson($msg);
        }
        $model = new \app\user\model\User();
        $info = $model->where($data)->find();
        if ($info) {
            $msg['msg'] = '获取成功';
            $msg['data'] = $info;
            return $this->successJson($msg);
        } else {

            $msg['msg'] = '获取失败';
            $msg['error_id'] = '1-01-01-0007';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 查询列表用户信息
     * @description 查询列表用户信息
     * @author 李锐志
     * @author 宋晓文
     * $edit_time 2018-12-27
     * @url /user/user/get_list
     * @method *
     * @param name:token require:1 default: desc:token
     * @param name:page require:1 default: desc:第几页
     * @param name:pagesize require:1 default: desc:每页数
     * @return list:用户信息@
     * @list    id:id    nickname:昵称    point_value:积分    signature:个性签名    head_img:头像    sex:性别.男:man;女:woman;保密:secrecy    hometown:家乡    phone:手机    password:密码    position:职位    qr_code:微信二维码    message_quantity:站内信数量    user_type:用户类型.普通用户:common_user;设计师:stylist;心理师:psychologist    is_show:是否首页显示
     * @return error_id:1-01-01-0006 校验失败
     */
    public function get_list()
    {
        $model = new \app\user\model\User();
        $Fields = $model->getTableFields();
        $data = \think\facade\Request::only($Fields);

        $where = array();
        foreach ($data as $k => $v) {
            if ($v === 0) {
                continue;
            }
            if ($v == null) {
                unset($data[$k]);
            }
        }
        foreach ($data as $k => $v) {
            if ($k === 'id' || $k === 'phone' || $k === 'sex' || $k === 'point_value' || $k === 'message_quantity' || $k === 'user_type' || $k === 'is_show') {
                array_push($where, [$k, '=', $data[$k]]);
                continue;
            }
            if (isset($data[$k]) && $data[$k] && !empty($data[$k])) {
                array_push($where, [$k, 'like', "%{$data[$k]}%"]);
            }
        }

        /**
         *$validate = new \app\user\validate\User();
         *$validate->scene('lists');
         *$result = $validate->batch(true)->check($data);
         *if ($result !== true) {
         *$msg['msg']='校验失败';
         *$msg['validate']=$validate->getError();
         *$msg['error_id']='1-01-01-0006';
         *return $this->errorJson($msg);
         *}
         **/
        $list = $model->where($where)->order('id', 'desc')->paginate();
        $msg['list'] = $list;
        return $this->successJson($msg);
    }

    /**
     * @title 前台头像修改
     * @description 前台头像修改
     * @author 李锐志
     * @url /user/user/change_head
     * @param name:token require:1 default: desc:token
     * @param name:head_img require:1 default: desc:图片地址
     * @method *
     */
    public function change_head()
    {
        Db::name('user')
            ->where('id', USERID)
            ->setField('head_img', input('head_img'));
        $msg['msg'] = '头像修改成功';
        return $this->successJson($msg);
    }

    /**
     * @title 前台修改密码
     * @description 前台修改密码
     * @author 李锐志
     * @url /user/user/change_password
     * @param name:token require:1 default: desc:token
     * @param name:old_password require:1 default: desc:旧密码
     * @param name:password require:1 default: desc:新密码
     * @param name:password_confirm require:1 default: desc:确认新密码
     * @method *
     */
    public function change_password()
    {
        $data = input();

        $validate = new Validate([
            'token' => 'require',
            'old_password' => 'require',
            'password' => 'require|confirm|length:6,18',
            'password_confirm' => 'require'
        ]);

        if (!$validate->check($data)) {
            $msg['msg'] = $validate->getError();
            return $this->successJson($msg);
        }

        $old_password = Db::name('user')
            ->where('id', USERID)
            ->value('password');
        if ($old_password !== md5($data['old_password'])) {
            $msg['msg'] = '旧密码错误!';
            return $this->errorJson($msg);
        }

        Db::name('user')
            ->where('id', USERID)
            ->setField('password', md5($data['password']));

        $msg['msg'] = '密码修改成功';
        return $this->successJson($msg);
    }

    /**
     * @title 前台通过token获取用户信息
     * @description 前台通过token获取用户信息
     * @author 李锐志
     * @url /user/user/token_get_user_information
     * @param name:token require:1 default: desc:token
     * @method *
     */
    public function token_get_user_information()
    {
        $result = Db::name('user')
            ->where('id', USERID)
            ->field('password,is_show', true)
            ->find();

        $msg['msg'] = '用户信息获取成功';
        $msg['data'] = $result;
        return $this->successJson($msg);
    }

    /**
     * @title 前台通过id获取用户信息
     * @description 前台通过id获取用户信息
     * @author 李锐志
     * @url /user/user/get_user_information
     * @param name:id require:1 default: desc:用户id
     * @method *
     */
    public function get_user_information()
    {
        $id = input('id');
        $result = Db::name('user')
            ->where('id', $id)
            ->field('password,is_show,message_quantity', true)
            ->find();

        $msg['msg'] = '用户信息获取成功';
        $msg['data'] = $result;
        return $this->successJson($msg);
    }

    /**
     * @title 前台首页设计师
     * @description 前台首页设计师
     * @author 李锐志
     * @url /user/user/homepage_stylist
     * @method *
     */
    public function homepage_stylist()
    {
        $result = Db::name('user')
            ->where('user_type', 'stylist')
            ->where('is_show', 1)
            ->order('id', 'desc')
            ->limit(6)
            ->select();

        $msg['msg'] = '首页设计师获取成功';
        $msg['list'] = $result;
        return $this->successJson($msg);
    }

    /**
     * @title 前台首页心理师
     * @description 前台首页心理师
     * @author 李锐志
     * @url /user/user/homepage_psychologist
     * @method *
     */
    public function homepage_psychologist()
    {
        $result = Db::name('user')
            ->where('user_type', 'psychologist')
            ->where('is_show', 1)
            ->order('id', 'desc')
            ->limit(6)
            ->select();

        $msg['msg'] = '首页心理师获取成功';
        $msg['list'] = $result;
        return $this->successJson($msg);
    }

    /**
     * @title 前台注册
     * @description 前台注册
     * @author 李锐志
     * @url /user/user/register
     * @method *
     * @param name:phone require:1 default: desc:手机
     * @param name:code require:1 default: desc:验证码
     * @param name:password require:1 default: desc:密码
     * @param name:password_confirm require:1 default: desc:确认密码
     * @param name:user_protocol require:1 default: desc:用户协议
     * @param name:sku_id require:1 default: desc:第三方登录id
     */
    public function register()
    {
        $data = input();

        $validate = new Validate([
            'phone' => 'require|mobile',
            'code' => 'require',
            'password' => 'require|confirm|length:6,18',
            'password_confirm' => 'require',
        ]);

        if (!$validate->check($data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }

        //判断是否勾选用户协议
        if (!isset($data['user_protocol'])) {
            $msg['msg'] = '没有勾选用户协议，无法注册';
            return $this->errorJson($msg);
        }

        //判断注册的手机号是否存在
        $phone = Db::name('user')
            ->where('phone', $data['phone'])
            ->field('phone')
            ->find();

        if ($phone) {
            $msg['msg'] = '该手机号已注册';
            return $this->errorJson($msg);
        }

        //判断验证码是否存在
        $arr = [
            'mobile' => $data['phone'],
            'code' => $data['code'],
            'code_type' => 'register',
        ];
        $check = get_curl('user', 'verification_code/check', $arr);

        if ($check['status'] === true) {
            //一致时，保存，并返回正确信息
            $insert['phone'] = $data['phone'];
            $insert['password'] = md5($data['password']);
            $insert['nickname'] = $data['phone'];
            $insert['signature'] = '该用户很懒，什么都没写。';
            $insert['head_img'] = HOST . "/public/upload/avatar.png";
            $user_id = Db::name('user')
                ->insertGetId($insert);
            if (isset($data['sdk_id'])) {
                Db::name('sdk_login')
                    ->where('id',$data['sdk_id'])
                    ->setField('user_id',$user_id);
                //随机生成20位字符串
                $token_str = substr(str_shuffle('abcedfghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20);

                //token表需要的字段
                $token['user_id'] = $user_id;
                $token['token'] = $token_str;
                $token['expires_in'] = 3600;             //有效期60分钟
                $token['create_time'] = time();
                $token['end_time'] = $token['create_time'] + $token['expires_in'];

                //写入token表
                get_curl('login','/token/add',$token);
                $msg['msg'] = '绑定成功';
                $msg['token'] = $token_str;
                return $this->successJson($msg);
            } else {
                $msg['msg'] = '注册成功';
                $msg['user_id'] = $user_id;
                return $this->successJson($msg);
            }

        } else {
            $msg['msg'] = '验证码有误';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 前台忘记密码
     * @description 前台忘记密码
     * @author 李锐志
     * @url /user/user/update_password
     * @method *
     * @param name:phone require:1 default: desc:手机
     * @param name:code require:1 default: desc:验证码
     * @param name:password require:1 default: desc:密码
     * @param name:password_confirm require:1 default: desc:确认密码
     */
    public function update_password()
    {
        $data = input();

        $validate = new Validate([
            'phone' => 'require|mobile',
            'code' => 'require',
            'password' => 'require|confirm|length:6,18',
            'password_confirm' => 'require',
        ]);

        if (!$validate->check($data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }

        //判断验证码是否存在
        $arr = [
            'mobile' => $data['phone'],
            'code' => $data['code'],
            'code_type' => 'update_password',
        ];

        $check = get_curl('user', 'verification_code/check', $arr);

        if ($check['status'] === true) {
            Db::name('user')
                ->where('phone', $data['phone'])
                ->update([
                    'password' => md5($data['password'])
                ]);
            $msg['msg'] = '密码修改成功';
            return $this->successJson($msg);
        } else {
            $msg['msg'] = '密码修改失败,验证码错误';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 前台设计师,心理师更多
     * @description 前台设计师,心理师更多
     * @author 李锐志
     * @url /user/user/get_more
     * @method *
     * @param name:user_type require:1 default: desc:用户类型(设计师:stylist;心理师:psychologist)
     * @param name:page require:1 default: desc:第几页
     * @param name:pagesize require:1 default: desc:每页数
     */
    public function get_more()
    {
        $user_type = input('user_type');
        $user = Db::name('user')
            ->where('user_type', $user_type)
            ->field('id,nickname,point_value,head_img,position')
            ->paginate();
        $user = $user->toArray();

        foreach ($user['data'] as $k => $v) {
            $topic = get_curl('topic', '/topic/get_user_topic', ['id' => $v['id'], 'page' => 1, 'pagesize' => 4])['data'];
            $user['data'][$k]['topic'] = $topic['data'];
        }

        $msg['msg'] = '获取成功';
        $msg['data'] = $user;
        return $this->successJson($msg);
    }

    /**
     * @title 前台给评论用户添加积分
     * @description 前台给评论用户添加积分
     * @author 李锐志
     * @url /user/user/comment_add_integral
     * @method *
     * @param name:token require:1 default: desc:token
     */
    public function comment_add_integral()
    {
        $integral = $this->system_config('comment_integral');

        Db::name('user')
            ->where('id', USERID)
            ->setInc('point_value', $integral);

        $msg['msg'] = '添加成功';
        return $this->successJson($msg);
    }

    /**
     * @title 前台给发帖用户添加积分
     * @description 前台给发帖用户添加积分
     * @author 李锐志
     * @url /user/user/topic_add_integral
     * @method *
     * @param name:token require:1 default: desc:token
     */
    public function topic_add_integral()
    {
        $integral = $this->system_config('topic_integral');

        Db::name('user')
            ->where('id', USERID)
            ->setInc('point_value', $integral);

        $msg['msg'] = '添加成功';
        return $this->successJson($msg);
    }

    /**
     * @title 前台修改个人信息
     * @description 前台修改个人信息
     * @author 李锐志
     * @url /user/user/edit_user_info
     * @method *
     * @param name:token require:1 default: desc:token
     * @param name:nickname require:1 default: desc:用户名
     * @param name:signature require:1 default: desc:个性签名
     * @param name:sex require:1 default: desc:性别
     * @param name:hometown require:1 default: desc:家乡
     * @param name:position require:1 default: desc:职称
     * @param name:qr_code require:1 default: desc:二维码
     */
    public function edit_user_info()
    {
        $data = input();
        $name_len = mb_strlen($data['nickname']);
        if ($name_len < 1 || $name_len > 12) {
            $msg['msg'] = '修改失败 用户名长度1~12';
            return $this->errorJson($msg);
        }
        Db::name('user')
            ->where('id', USERID)
            ->strict(false)
            ->update($data);

        $msg['msg'] = '修改成功';
        return $this->successJson($msg);
    }

    /**
     * @title 前台修改个人站内信数量
     * @description 前台修改个人站内信数量
     * @author 李锐志
     * @url /user/user/edit_message
     * @method *
     * @param name:id require:1 default: desc:id
     * @param name:quantity require:1 default: desc:数量
     */
    public function edit_message()
    {
        $data = input();

        Db::name('user')
            ->where('id', $data['id'])
            ->setField('message_quantity', $data['quantity']);

        $msg['msg'] = '编辑成功';
        return $this->successJson($msg);
    }
}
